/*
 *      net-sim - link
 *
 * 		Linksender.java
 *
 *      Copyright 23/12/2008 nicolas
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 3 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */
package link;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.LinkedList;

/**
 * The Class Linksender.
 */
public class Linksender extends Thread {

  /** Socket de envio. */
  static DatagramSocket socket;

  /** Port del socket de envio. */
  static int remport=0;

  /** IP del socket de envio. */
  static InetAddress remaddr=null;

  /** Cola de transmision de frames. */
  LinkedList transmitionQueue;

  /** The link. */
  static Link link;

  /**
   * Instantiates a new linksender.
   *
   * @param lnk the lnk
   * @param sock the sock
   * @param dip the dip
   * @param dport the dport
   */
  public Linksender(Link lnk, DatagramSocket sock, InetAddress dip, int dport)  {
    socket = sock;
    this.link = lnk;
    remport = dport;
    remaddr = dip;
    //TQueue = new Utils.Queue();
    transmitionQueue = null;
    this.start();
  }

  /**
   * Sets the queue.
   *
   * @param T the new queue
   */
  public void setQueue(LinkedList T) {
    transmitionQueue = T;
  }

  /**
   *  Envia un frame a la direccion remota esto deberia ser private, es solo prueba.
   *
   * @param frame the frame
   */
  static void enviar(byte[] frame)  {
    try {
      socket.send(new DatagramPacket(frame, frame.length, remaddr, remport));
    }
    catch(IOException e) {
      //throw new NodeException(NodeException.EXCEPCION_ENVIO);
      System.out.println("Excepcion al enviar");
    }
  }

  // En el ciclo, envia os frames
  /* (non-Javadoc)
   * @see java.lang.Thread#run()
   */
  public void run() {
    while (true) {
      if(transmitionQueue != null) {
        while(transmitionQueue.size() != 0 ) {
          byte[] frame =  (byte[]) transmitionQueue.peekFirst();
          enviar(frame);
          transmitionQueue.removeFirst();
        }
      }
    }
  }
}

